package com.liukai.todo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liukai.todo.config.JwtUtil;
import com.liukai.todo.entity.RespBean;
import com.liukai.todo.entity.UserInfo;
import com.liukai.todo.mapper.UserMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liukai.todo.service.IUserService;
import com.liukai.todo.utils.RedisUtil;
import com.liukai.todo.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author liukai
 * @since 2021-07-30
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserInfo> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    private JwtUtil jwtUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Value("${verification.kaptcha-key}")
    private String kaptcha_key;
    @Value("${verification.expiration}")
    private long expiration;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UUIDUtil uuidUtil;

    /**
     * 登录之后返回token
     *
     * @param userName
     * @param passWord
     * @param request
     * @return
     */
    @Override
    public RespBean login(String userName, String passWord, HttpServletRequest request) {
//        String captcha = (String) request.getSession().getAttribute("captcha");
        String verification_head = request.getHeader("verification-head");
        String key = kaptcha_key + verification_head;
//        if (!redisUtil.hasKey(key)) {
//            return RespBean.error("验证码过期，请刷新验证码");
//        }
//        String kaptcha_code = (String) redisUtil.get(key);
//        if (kaptcha_code.isEmpty() || !kaptcha_code.equalsIgnoreCase(code)){
//            return RespBean.error("验证码输入错误，请重新输入");
//        }
        // 登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(userName);
        if (userDetails == null || !bCryptPasswordEncoder.matches(passWord, userDetails.getPassword())) {
            return RespBean.error("用户名或密码不正确");
        }
        if (!userDetails.isEnabled()) {
            return RespBean.error("账号被禁用，请联系管理员");
        }

        // 更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 生成token
        String token = jwtUtil.generateToken(userDetails);
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
//        tokenMap.put("verification-head",uuidUtil.getUUID());

        return RespBean.success("登录成功", tokenMap);

    }

    /**
     * 根据用户名获取用户
     *
     * @param userName
     * @return
     */
    @Override
    public UserInfo getUserInfoByUserName(String userName) {
        return userMapper
                .selectOne(new QueryWrapper<UserInfo>()
                        .eq("userName", userName));
    }

    /**
     * 根据userId获取用户信息
     *
     * @param userId
     * @return
     */
    @Override
    public UserInfo getUserInfoByUserId(Integer userId) {
        return userMapper.selectOne(new QueryWrapper<UserInfo>()
                .eq("userId", userId));
    }

    /**
     * 注册用户
     *
     * @param userInfo
     * @return
     */
    @Override
    public RespBean register(UserInfo userInfo) {
        UserInfo userInfo1 = getUserInfoByUserName(userInfo.getUsername());
        if (userInfo1 != null) {
            return RespBean.error("注册失败，该账号已被注册");
        }
        String newPassword = bCryptPasswordEncoder.encode(userInfo.getUserPass());
        userInfo.setUserPass(newPassword);
        int i = userMapper.insert(userInfo);
        if (i >= 0) {
            return RespBean.success("注册成功");
        }
        return RespBean.error("注册失败");
    }

    /**
     * 根据userId删除用户（注销）
     *
     * @param userId
     * @return
     */
    @Override
    public int deleteUserByUserId(Integer userId) {
        return userMapper.deleteById(userId);
    }

    /**
     * 根据userId修改用户信息
     *
     * @param userInfo
     * @return
     */
    @Override
    public int updateUserByUserId(UserInfo userInfo) {
        String newPassword = bCryptPasswordEncoder.encode(userInfo.getUserPass());
        userInfo.setUserPass(newPassword);
        return userMapper.updateById(userInfo);
    }
}
